package cur.tool.common;

import cur.nature.framework.core.log.LOG;
import cur.nature.framework.core.thread.MyThreadLocal;
import cur.nature.framework.core.util.JWTUtil;
import cur.nature.framework.mvc.auth.LoginUser;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Component
public class AppContextUtil {

    @Value("${cur.core.server.config.mvc.ignoreUri}")
    private List<String> ignoreUri;

    @Value("${cur.core.server.config.mvc.swagger:false}")
    private Boolean swaggerOn;

    @Value("${cur.component.prometheus.enable:false}")
    private Boolean prometheusOn;

    private static AppContextUtil _self;

    @PostConstruct
    public void init() {
        _self = this;
    }

    private static LoginUser getUser(HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            Object attribute = session.getAttribute(session.getId());
            if(attribute == null){
                //校验 token
                String token = request.getHeader(MyThreadLocal.TOKEN);
                JWTUtil.Result result = JWTUtil.decodeToken(token);
                LoginUser.User user = new LoginUser.User();
                user.setId(result.getData());
                LoginUser loginUser = new LoginUser();
                loginUser.setUserInfo(user);
                return loginUser;
            }
            return (LoginUser) attribute;
        }catch (Exception ex) {
            LOG.warn("获取用户信息异常, " + ex.getMessage());
        }
        return null;
    }
    public static String getUserId(HttpServletRequest request){
        try{
            LoginUser user = getUser(request);
            return (user==null)? null : user.getUserInfo().getId();
        }catch (Exception ex){
            LOG.warn("获取用户id异常: " + ex.getMessage());
        }
        return "0";

    }

    public static String getURI(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        return requestURI;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }

    public static Boolean isIgnoreURL(String requestURI){
        boolean ignore = false;
        //过滤swagger请求
        if(_self.swaggerOn){
            final boolean swaggerPass = requestURI.equals("/v3/api-docs/swagger-config")  || requestURI.equals("/doc.html")
                    || (requestURI.indexOf("/v3/api-docs") != -1);
            ignore = swaggerPass;
        }
        // 过滤prometheus请求
        if (_self.prometheusOn) {
            final boolean pass = requestURI.equals("/actuator/prometheus");
            ignore = pass;
        }
        // 过滤ingore请求
        if (!ignore &&_self.ignoreUri != null && _self.ignoreUri.contains(requestURI)){
            ignore = true;
        }
        return ignore;
    }

    public static Boolean isIgnoreURLWithLog(String requestURI){
        boolean ignore = isIgnoreURL(requestURI);
        if (ignore && (requestURI.equalsIgnoreCase("/manager/Admin_User/login")
                || requestURI.equalsIgnoreCase("/manager/Admin_User/logout"))) {
            ignore = false;
        }
        return ignore;
    }
}
